/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package com.yasee.chronic.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.ConsumerIrManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.yasee.chronic.R;
import com.yasee.chronic.activity.UserActivity;
import com.yasee.chronic.adapter.UserAdapter;
import com.yasee.chronic.adapter.UserDetailAdapter;
import com.yasee.chronic.model.DeptInfo;
import com.yasee.chronic.model.User;
import com.yasee.chronic.model.WorkBean;
import com.yasee.chronic.util.HttpRequest;
import com.yasee.chronic.util.MyUtils;
import com.yasee.chronic.util.TestUtil;
import com.yasee.chronic.widget.MyDialog;
import com.yasee.gson.Gson;

import zuo.biao.library.base.BaseHttpListFragment;
import zuo.biao.library.interfaces.AdapterCallBack;
import zuo.biao.library.interfaces.CacheCallBack;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.util.CommonUtil;
import zuo.biao.library.util.JSON;
import zuo.biao.library.util.Log;

/**
 * 用户列表界面fragment
 *
 * @author Lemon
 * @use new UserListFragment(),详细使用见.DemoFragmentActivity(initData方法内)
 * @must 查看 .HttpManager 中的@must和@warn
 * 查看 .SettingUtil 中的@must和@warn
 */
public class UserListFragment extends BaseHttpListFragment<WorkBean.Data, ListView, UserAdapter> implements CacheCallBack<WorkBean.Data>, View.OnClickListener {
    private static final String TAG = "UserListFragment";

    //与Activity通信<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    String dataType = "all";

    List<DeptInfo.Children> deptList = new ArrayList<>();
    List<DeptInfo.Children> deptLastList = new ArrayList<>();
    DeptInfo deptInfo = new DeptInfo();
    // 路径栈，用于存储用户选择的路径
    private Stack<List<DeptInfo.Children>> pathStack = new Stack<>();
    LinearLayout llDept;

    private ImageView ivSearch;
    private EditText etKeyWords;

    private LinearLayout rlTitle;
    private TextView tvTitle;
    private ImageView ivTitle;

    private List<WorkBean.Data> workList = new ArrayList<>();

    public static final String ARGUMENT_RANGE = "ARGUMENT_RANGE";

    private SmartRefreshLayout srlBaseHttpList1;
    private GridView gvBaseList;
    UserDetailAdapter userDetailAdapter;

    public static UserListFragment createInstance(int range) {
        UserListFragment fragment = new UserListFragment();

        Bundle bundle = new Bundle();
        bundle.putInt(ARGUMENT_RANGE, range);

        fragment.setArguments(bundle);
        return fragment;
    }

    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    private ConsumerIrManager consumerIrManager;

    public static final int RANGE_ALL = HttpRequest.USER_LIST_RANGE_ALL;
    public static final int RANGE_RECOMMEND = HttpRequest.USER_LIST_RANGE_RECOMMEND;

    private TextView tvDept;

    private int range = RANGE_ALL;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.fragment_userlist);
        argument = getArguments();
        if (argument != null) {
            range = argument.getInt(ARGUMENT_RANGE, range);
        }


        initCache(this);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        consumerIrManager = (ConsumerIrManager) context.getSystemService(Context.CONSUMER_IR_SERVICE);

        if (consumerIrManager.hasIrEmitter()) {
            showShortToast("支持红外");
        } else {
            showShortToast("不支持红外");
        }

        srlBaseHttpList.autoRefresh();

        return view;
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initView() {//必须调用
        super.initView();
        llDept = findView(R.id.llDept);
        tvDept = findView(R.id.tvDept);
        ivSearch = findView(R.id.iv_search);
        etKeyWords = findView(R.id.etKeyWords);

        rlTitle = findView(R.id.rl_title);
        tvTitle = findView(R.id.tv_title);
        ivTitle = findView(R.id.iv_title);

        srlBaseHttpList1 = findView(R.id.srlBaseHttpList1);
        gvBaseList = findView(R.id.gvBaseList);
    }

    @Override
    public void setList(List<WorkBean.Data> list) {
        setList(new AdapterCallBack<UserAdapter>() {

            @Override
            public UserAdapter createAdapter() {
                return new UserAdapter(context);
            }

            @Override
            public void refreshAdapter() {
                adapter.refresh(list);
            }
        });
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initData() {//必须调用
        super.initData();
        getDeptList();
    }

    private void getDeptList() {
        HttpRequest.getDeptList(0, new OnHttpResponseListener() {
            @Override
            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                if (e != null) {
                    Log.e(TAG, "initData  HttpRequest.getDeptList  e = " + e.getMessage());
                } else {
                    deptInfo = new Gson().fromJson(resultJson, DeptInfo.class);
                    deptList = deptInfo.getData().get(0).getChildren();
                    tvDept.setText(findDeptNameById(deptInfo.getData(), CommonUtil.deptId));
                    getListAsync(0);
                }
            }
        });
    }

    @Override
    public void getListAsync(final int page) {
        //实际使用时用这个，需要配置服务器地址		HttpRequest.getUserList(range, page, -page, this);
        if (etKeyWords.getText().toString().trim().isEmpty()) {
            HttpRequest.getUserList(dataType, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    Log.e(TAG, "getListAsync  onHttpResponse  resultJson = " + resultJson);
                    if (e != null) {
                        Log.e(TAG, "initData  HttpRequest.getDeptList  e = " + e.getMessage());
                    } else {
                        WorkBean workBean = new Gson().fromJson(resultJson, WorkBean.class);
                        if (workBean.getSuccess()) {
                            if(dataType.equals("all")){
                                srlBaseHttpList.finishRefresh();
                                srlBaseHttpList.finishLoadMore();
                                onLoadSucceed(0, workBean.getData());
                            }else{
                                srlBaseHttpList1.finishRefresh();
                                srlBaseHttpList1.finishLoadMore();
                                userDetailAdapter = new UserDetailAdapter(context);
                                userDetailAdapter.setType(dataType);
                                gvBaseList.setAdapter(userDetailAdapter);
                                userDetailAdapter.refresh(workBean.getData());
                            }
                        } else {
                            showShortToast(workBean.getMsg());
                        }
                    }

                }
            });
        } else {
            HttpRequest.getUserList(dataType, etKeyWords.getText().toString().trim(), 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    Log.e(TAG, "getListAsync  onHttpResponse  resultJson = " + resultJson);
                    if (e != null) {
                        Log.e(TAG, "initData  HttpRequest.getDeptList  e = " + e.getMessage());
                    } else {
                        WorkBean workBean = new Gson().fromJson(resultJson, WorkBean.class);
                        if (workBean.getSuccess()) {
                            workList = workBean.getData();
                            if(dataType.equals("all")){
                                onLoadSucceed(0, workBean.getData());
                                srlBaseHttpList.finishRefresh();
                                srlBaseHttpList.finishLoadMore();
                            }else{
                                srlBaseHttpList1.finishRefresh();
                                srlBaseHttpList1.finishLoadMore();
                                userDetailAdapter = new UserDetailAdapter(context);
                                userDetailAdapter.setType(dataType);
                                gvBaseList.setAdapter(userDetailAdapter);
                                userDetailAdapter.refresh(workBean.getData());
                            }
                        } else {
                            showShortToast(workBean.getMsg());
                        }
                    }

                }
            });
        }
    }

    String resNum = "";

    public void getScanResult(String scanResult) {
        HttpRequest.getScanResult(scanResult, 0, new OnHttpResponseListener() {
            @Override
            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                if (e != null) {
                    Log.e(TAG, "initData  HttpRequest.getDeptList  e = " + e.getMessage());
                } else {
                    Log.e(TAG, "扫码请求返回值：" + resultJson);
                    Map<String, Object> map = new Gson().fromJson(resultJson, Map.class);
                    String data = map.get("data").toString();
                    resNum = data;
                    srlBaseHttpList.setEnableAutoLoadMore(false);
                    srlBaseHttpList.setEnableLoadMore(false);
                    getUserByResNum();
                }
            }
        });
    }

    private void getUserByResNum() {
        HttpRequest.getUserListByRes(dataType, resNum.trim(), 0, new OnHttpResponseListener() {
            @Override
            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                Log.e(TAG, "getListAsync  onHttpResponse  resultJson = " + resultJson);
                if (e != null) {
                    Log.e(TAG, "initData  HttpRequest.getDeptList  e = " + e.getMessage());
                } else {
                    WorkBean workBean = new Gson().fromJson(resultJson, WorkBean.class);
                    if (workBean.getSuccess()) {
                        workList = workBean.getData();
                        if(dataType.equals("all")){
                            srlBaseHttpList.finishRefresh();
                            srlBaseHttpList.finishLoadMore();
                            onLoadSucceed(0, workBean.getData());
                        }else{
                            srlBaseHttpList1.finishRefresh();
                            srlBaseHttpList1.finishLoadMore();
                            userDetailAdapter = new UserDetailAdapter(context);
                            userDetailAdapter.setType(dataType);
                            gvBaseList.setAdapter(userDetailAdapter);
                            userDetailAdapter.refresh(workBean.getData());
                        }
                    } else {
                        showShortToast(workBean.getMsg());
                    }
                }

            }
        });
    }

    @Override
    public List<WorkBean.Data> parseArray(String json) {
        return JSON.parseArray(json, WorkBean.Data.class);
    }


    @Override
    public Class<WorkBean.Data> getCacheClass() {
        return WorkBean.Data.class;
    }

    @Override
    public String getCacheGroup() {
        return "range=" + range;
    }

    @Override
    public String getCacheId(WorkBean.Data data) {
        return data == null ? null : "" + data.getUserId();
    }


    @Override
    public int getCacheCount() {
        return 10;
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    @Override
    public void initEvent() {//必须调用
        super.initEvent();
        llDept.setOnClickListener(this);
        ivSearch.setOnClickListener(this);
        rlTitle.setOnClickListener(this);
        srlBaseHttpList.setEnableLoadMore(false);
        srlBaseHttpList.setEnableAutoLoadMore(false);
        srlBaseHttpList.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getListAsync(0);
            }
        });
        srlBaseHttpList.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                srlBaseHttpList.finishLoadMore();
            }
        });

        srlBaseHttpList1.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getListAsync(0);
            }
        });

        srlBaseHttpList1.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                srlBaseHttpList1.finishLoadMore();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (id > 0) {
            toActivity(UserActivity.createIntent(context, id));
        }
    }


    //生命周期、onActivityResult<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    //生命周期、onActivityResult>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    private void showUserListDialog(List<DeptInfo.Children> list) {
        // 创建用户列表对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("选择科室");
        // 创建ListView
        ListView listView = new ListView(context);
        // 使用传统循环转换
        List<String> usernames = new ArrayList<>();
        for (DeptInfo.Children user : list) {
            if (user.getIsChoice()) {
                usernames.add(user.getName());
            }
        }

        Log.e(TAG, "users++++++++" + usernames.size());

        ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, usernames);
        listView.setAdapter(adapter);

        MyDialog dialog1 = new MyDialog(context, MyDialog.DialogType.NORMAL);

        dialog1.setTitle("选择科室");
        dialog1.setLeftButton("返回", new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                getScanResult("PID|张艳^2024445687^39|家庭住址：青岛市");
                dialog1.dismiss();
                if (!pathStack.isEmpty()) {
                    if (pathStack.get(pathStack.size() - 1).equals(list)) {
                        pathStack.clear();
                    } else {
                        showUserListDialog(pathStack.pop());
                    }
                }
            }
        });

        // 设置ListView的点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 处理用户选择事件
                dialog1.dismiss();
                if (list.get(position).getChildren() == null || list.get(position).getChildren().size() == 0) {
                    CommonUtil.deptId = list.get(position).getId();
                    Log.e(TAG, "CommonUtil.deptId++++++++" + CommonUtil.deptId);
                    tvDept.setText(list.get(position).getName());
                    getListAsync(0);
                } else {
                    showUserListDialog(list.get(position).getChildren());
                    // 有子节点，将当前列表压入路径栈
                    pathStack.push(list);
                    deptLastList = list;
                }
            }
        });
        dialog1.setCustomView(listView);
        dialog1.show();
    }

    private void showPopupWindow(View anchorView) {
        // 创建一个布局文件，例如popup_window.xml
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popupView = inflater.inflate(R.layout.popup_window, null);

        // 创建PopupWindow
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = LinearLayout.LayoutParams.MATCH_PARENT - MyUtils.dip2px(50);
        boolean focusable = true; // 是否允许PopupWindow获取焦点
        final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

        // 设置背景
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#80000000")));

        LinearLayout llBloodAll = popupView.findViewById(R.id.ll_blood_all);
        LinearLayout llBloodSugar = popupView.findViewById(R.id.ll_blood_sugar);
        LinearLayout llBloodPressure = popupView.findViewById(R.id.ll_blood_pressure);
        LinearLayout llUricAcid = popupView.findViewById(R.id.ll_uric_acid);
        LinearLayout llBloodKetone = popupView.findViewById(R.id.ll_blood_ketone);

        llBloodAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataType = "all";
                popupWindow.dismiss();
                tvTitle.setText("工作台");
                srlBaseHttpList.setVisibility(View.VISIBLE);
                srlBaseHttpList1.setVisibility(View.GONE);
                getListAsync(0);
            }
        });
        llBloodSugar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataType = "bg";
                popupWindow.dismiss();
                tvTitle.setText("血糖工作台");
                srlBaseHttpList.setVisibility(View.GONE);
                srlBaseHttpList1.setVisibility(View.VISIBLE);
                getListAsync(0);
            }
        });
        llBloodPressure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataType = "bp";
                popupWindow.dismiss();
                tvTitle.setText("血压工作台");
                srlBaseHttpList.setVisibility(View.GONE);
                srlBaseHttpList1.setVisibility(View.VISIBLE);
                getListAsync(0);
            }
        });
        llUricAcid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataType = "ua";
                popupWindow.dismiss();
                tvTitle.setText("尿酸工作台");
                srlBaseHttpList.setVisibility(View.GONE);
                srlBaseHttpList1.setVisibility(View.VISIBLE);
                getListAsync(0);
            }
        });
        llBloodKetone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataType = "bk";
                popupWindow.dismiss();
                tvTitle.setText("血酮工作台");
                srlBaseHttpList.setVisibility(View.GONE);
                srlBaseHttpList1.setVisibility(View.VISIBLE);
                getListAsync(0);
            }
        });

        // 显示PopupWindow
        popupWindow.showAsDropDown(anchorView);

        // 设置点击外部关闭PopupWindow
        popupView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                popupWindow.dismiss();
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llDept:
                showUserListDialog(deptList);
                break;
            case R.id.iv_search:
                getListAsync(0);
                break;
            case R.id.rl_title:
                showPopupWindow(findView(R.id.rlBottomTabTopbar));
                break;
            default:
                break;
        }
    }

    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    // 遍历deptList，取出id为指定字符的name
    private String findDeptNameById(List<DeptInfo.Children> list, String targetId) {
        for (DeptInfo.Children dept : list) {
            if (dept.getId().equals(targetId)) {
                return dept.getName();
            }
            if (dept.getChildren() != null && !dept.getChildren().isEmpty()) {
                String name = findDeptNameById(dept.getChildren(), targetId);
                if (name != null) {
                    return name;
                }
            }
        }
        return null;
    }


    //内部类,尽量少用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    //内部类,尽量少用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


}